// -*- coding: utf-8 -*- 
/**
 * Project: AlgorithmsLearn
 *
 * @author: yanking
 * Create time: 2022-03-29 15:55
 * IDE: IntelliJ IDEA
 * Introduction:
 */
package com.LeetCodeT.DateTrain;

import org.junit.jupiter.api.Test;

/**
 * 最长连续答案长度
 */
public class MaxConsecutiveAnswers {
    public int maxConsecutiveAnswers(String answerKey, int k) {
        int n = answerKey.length();
        if (n < 2) {
            return n;
        }
        /*
            滑动窗口 -> k是容错率
            因为T和F不一样，所以可以遍历两次
         */
        int L = 0, R = 0, cnt = k;
        int TMax = getRes(answerKey, 'T', k);
        int FMax = getRes(answerKey, 'F', k);
        return Math.max(TMax, FMax);
    }


    private int getRes(String answerKey, char answer, int cnt) {
        int L = 0, R = 0, n = answerKey.length(), res = 0, k = cnt;
        /*-----初始化位置-----*/
        while (answerKey.charAt(R) != answer) {
            R++;
        }
        L = R;
        while (R < n) {
            tag:
            if (answerKey.charAt(R) != answer || R == n - 1) {
                if (cnt <= 0) {
                    while (L < R && answerKey.charAt(L) == answer) {
                        L++;
                    }
                    L += 1;
                    cnt += 1;
                    break tag;
                }
                cnt--;
            }
            res = Math.max(res, R - L + 1);
            ++R;
        }
        return res;
    }

    @Test
    public void shout() {
        //String test = "TTFF";
        //String test = "TTFTTFTT";
        String test = "FFFTTFTTFT";
        System.out.println(maxConsecutiveAnswers(test, 3));
    }
}
